package com.sky.controller.admin;


import com.github.xiaoymin.knife4j.core.util.CollectionUtils;
import com.sky.dto.DishDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.result.Result;
import com.sky.service.IDishFlavorService;
import com.sky.service.IDishService;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * <p>
 * 菜品 前端控制器
 * </p>
 *
 * @author author
 * @since 2024-07-19
 */
@RestController
@RequestMapping("/admin/dish")
@RequiredArgsConstructor
@Slf4j
@Api(tags = "菜品相关接口")
public class DishController {
    private final IDishService iDishService;
    private final IDishFlavorService iDishFlavorService;
    @PostMapping("")
    public Result<String> saveWithFlavor(@RequestBody DishDTO dishDTO){
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        iDishService.save(dish);
        //同时要插入多条口味，对应这里的菜品id
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if(CollectionUtils.isNotEmpty(flavors)){
            for (DishFlavor flavor : flavors) {
                flavor.setDishId(dish.getId());
            }
        }
        boolean result = iDishFlavorService.saveBatch(dishDTO.getFlavors());
        if(!result){
            return Result.error("新增菜品失败");
        }
        return Result.success();
    }
}
